//
// Created by jyh on 2021/7/30.
//
#include <stdio.h>
#include <string.h>
#include "Controller.h"
#include "Deploy.h"
#include "./Com.h"
#include "BaseStation.h"
#include "Rnxeph.h"
#include "StreamObs.h"

#include "initcfg.h"

struct Controller CTRL;

void Initialize(){
    // Initialize args
    char *args[4] = {"", "-mode", "vrs", "./vrs.json"}; //"-mode vrs vrs_jyh.json" "-sync";
    CTRL.m_argc = 4;
    memcpy(CTRL.m_args, args, sizeof(char *) * 4);
    if (CTRL.m_argc < 3) {
        printf("Welcome to bboSatChip!\n");
        printf("Example: bboVrsChip -mode vrs vrs.json\n");
        printf("Example: where (*) denotes optional parameter.\n");
        exit(1);
    }

    // Initialize configuration
    m_readJsonFile(CTRL.m_argc, CTRL.m_args);

    // Initialize DLY
    DLY.lastmjd = 0;
    DLY.lastsod = 0.0;

    // Initialize BRDM EPH & OBS
    Rnxeph_initial();
};

// main process
int inputBuf(char *buff, double stax[3], int mjd, double sod) {
    static int initflag=1;
    int i, nbyte, ref, isit = 0;
    clock_t begin, end;
    begin = clock();

    if(initflag) {
        Initialize();
        DLY.mjd = mjd;
        DLY.sod = sod;
        initflag = 0;
    }

    // Read BRDM EPH
/*    if(!(ref = StreamReader(buff, nbyte)))
            printf("*****WARNING: No brdm eph was received!\n");*/

    // If stax==0 || time==0, return 0.
    if((fabs(stax[0])+fabs(stax[1])+fabs(stax[2]))<1e-8 || (mjd*86400.0+sod)<1e-8){
        end = clock();
        printf("Saved EPH: GNSS %d, GLS %d\n", Sat_CountSat(false), Sat_CountSat(true));
        printf("*****##### Receive BRDM EPH: mjd=%d sod=%.2lf\t time consume: %lf(s)\n\n", DLY.mjd, DLY.sod, (double) (end - begin) / CLOCKS_PER_SEC);
        return 0;
    }

    // Compute Satellite Location, return 1.
    Sat_m_getSatLocation(&DLY.SIT[isit]);

    // Next
    end = clock();
    printf("Saved EPH: GNSS %d, GLS %d\n", Sat_CountSat(false), Sat_CountSat(true));
    printf("*****##### Computed Satellite Location: mjd=%d sod=%.2lf\t time consume: %lf(s)\n\n", DLY.mjd, DLY.sod, (double) (end - begin) / CLOCKS_PER_SEC);

    return 1;
}
void finish(){
    // End, free storage
    free(DLY.SAT);
    free(DLY.SIT);
    free(DLY.mRnxobs);
    free(DLY.m_reqs);
}



